package com.jhd.jiangxi.activity.main;

import android.content.Context;
import android.content.DialogInterface;

import androidx.appcompat.app.AlertDialog;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.jhd.jiangxi.R;
import com.jhd.jiangxi.UtilHelper;
import com.jhd.jiangxi.downloadmanager.Utils.DeviceUtils;
import com.jhd.jiangxi.service.VaccineService;
import com.jhd.jiangxi.vo.Approval;
import com.jhd.jiangxi.vo.JsonForResult;
import com.jhd.jiangxi.vo.PriceBook;
import com.jhd.jiangxi.vo.RefDept;
import com.jhd.jiangxi.vo.Storage;

import net.zigin.commons.util.StringUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/*登录后的配置界面*/
public class ConfigActivity extends BaseActivity {
    private Context context=ConfigActivity.this;
    private AlertDialog _alertDialog = null; //单选框

    @BindView(R.id.btnRefDept)TextView btnRefDept;
    @BindView(R.id.btnPriceBookIn)TextView btnPriceBookIn;
    @BindView(R.id.btnApprovalIn)TextView btnApprovalIn;
    @BindView(R.id.btnVaccineType)TextView btnVaccineType;
    @BindView(R.id.btnStorage)TextView btnStorage;
    @BindView(R.id.btnBackSystem)TextView btnBackSystem;
    @BindView(R.id.tvVersion)TextView tvVersion;
    private List<PriceBook> pbList=null;
    private List<Storage> storageList=null;
    private List<RefDept> refDeptList=null;
    private ListView listView;
    private PopupWindow popup;

    @OnClick({R.id.btnBack, R.id.btnVersion,R.id.btnRefDept,R.id.btnPriceBookIn,R.id.btnApprovalIn,R.id.btnVaccineType,R.id.btnStorage,R.id.btnBackSystem})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnBack:
                this.onBackPressed();
                break;
            case R.id.btnVersion:
                //new UpdateManager(this).checkUpdate(false);
                Toast.makeText(context,"暂无该功能!",Toast.LENGTH_SHORT).show();
                break;
            case R.id.btnRefDept:
                name.clear();id.clear();
                if(refDeptList!=null){
                    for (RefDept refDept : refDeptList) {
                        name.add(refDept.getName());
                        id.add(refDept.getRefDeptId());
                    }show(btnRefDept,name,id);
                }else{
                    Toast.makeText(context,"请检查网络,未拿到往来单位列表!",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btnPriceBookIn:
                name.clear();id.clear();
                if(pbList!=null){
                    for (PriceBook priceBook : pbList) {
                        name.add(priceBook.getPriceBookNo());
                        id.add(priceBook.getId());
                    }show(btnPriceBookIn,name,id);
                }else{
                    Toast.makeText(context,"请检查网络,未拿到价格本列表!",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btnApprovalIn:
                name.clear();id.clear();
                if(approvalList!=null){
                    for (Approval approval : approvalList) {
                        name.add(approval.getUserName1());
                        id.add(approval.getId());
                    }show(btnApprovalIn,name,id);
                }else{
                    Toast.makeText(context,"请检查网络,未拿到审批流列表!",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btnVaccineType:
                show(btnVaccineType, Arrays.asList(vaccineTypeItems),Arrays.asList(vaccineTypeValues));
                break;
            case R.id.btnStorage:
                name.clear();id.clear();
                if(storageList!=null){
                    for (Storage storage : storageList) {
                        name.add(storage.getName());
                        id.add(storage.getId());
                    }show(btnStorage,name,id);
                }else{
                    Toast.makeText(context,"请检查网络,未拿到储位列表!",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btnBackSystem:
                show(btnBackSystem,Arrays.asList(backSystemItems),Arrays.asList(backSystemValues));
                break;
        }
    }
    private final String[] vaccineTypeItems = {"免疫规划", "非免疫规划", "配套品"};
    private final String[] vaccineTypeValues = {"1", "2", "3"};
    private final List<String> name = new ArrayList<String>();
    private final List<String> id = new ArrayList<String>();
    private final String[] backSystemItems = {"正式系统", "测试系统"};
    private final String[] backSystemValues = {"1", "0"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_config);
        ButterKnife.bind(this);
        application.setBackSystem("1");//先默认正式系统
        tvVersion.setText("当前版本号:" + DeviceUtils.getVersionCode(this));
        initHeader3("系统设置");
        isConfig();//判断是否已经配置过,如果配置过就直接显示配置的值
        selectApproval();selectPriceBook();selectRefDept();selectStorage();
    }

    private void isConfig() {
        if(application.getConfigApprovalName()!=null){btnApprovalIn.setText(application.getConfigApprovalName());btnApprovalIn.setTextColor(getResources().getColor(R.color.billTextChoose));}
        if(application.getConfigDeptName()!=null){btnRefDept.setText(application.getConfigDeptName());btnRefDept.setTextColor(getResources().getColor(R.color.billTextChoose));}
        if(application.getConfigPriceNo()!=null){btnPriceBookIn.setText(application.getConfigPriceNo());btnPriceBookIn.setTextColor(getResources().getColor(R.color.billTextChoose));}
        if(application.getConfigStorageName()!=null){btnStorage.setText(application.getConfigStorageName());btnStorage.setTextColor(getResources().getColor(R.color.billTextChoose));}
        if(application.getConfigVaccineTypeName()!=null){btnVaccineType.setText(application.getConfigVaccineTypeName());btnVaccineType.setTextColor(getResources().getColor(R.color.billTextChoose));}
        if(application.getBackSystem()!=null){
            if(application.getBackSystem().equals("0")){btnBackSystem.setText("测试系统");}}
    }

    @Override
    public void onBackPressed() {
        if (application.getConfigVaccineTypeId() == null || application.getConfigStorageId() == null || application.getConfigPriceId() == null
                || application.getConfigDeptId() == null || application.getConfigApprovalId() == null) {
            String msg = "默认配置项没有完成,无法进入主界面,只能退回登录页,您确实要退至登录吗?";
            UtilHelper.dialogSelector(ConfigActivity.this, "退回登录", msg, new ConfigActivity.BackToLogin());
            return;
        }
        super.onBackPressed();
    }

    private void logout() {
        ConfigActivity.this.setResult(RESULT_FIRST_USER);
        ConfigActivity.this.finish();
    }

    private class BackToLogin implements UtilHelper.SelectOK {
        @Override
        public void execute() {
            logout();
        }
    }
    /*获取价格本列表*/
    private void selectPriceBook() {
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("deptId", application.getDeptId());
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.EMIAO(application.getBackSystem()));
        VaccineService vs = retrofit.create(VaccineService.class);
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = vs.getPriceBookMstList(token, params);
        jsonForResultCall.enqueue(new getPriceBookMstListCallback());
    }
    private class getPriceBookMstListCallback implements Callback<JsonForResult> {

        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                if (response.code() != 200) {
                    UtilHelper.alertMsg(ConfigActivity.this, "错误", response.code() + response.message());
                    return;
                }
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess()) {
                    pbList = JSON.parseArray(jsonForResult.getData().toString(), PriceBook.class);
                } else {
                    if (jsonForResult != null) {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                }
            } catch (Exception e) {
                Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "网络异常!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            UtilHelper.alertMsg(ConfigActivity.this, "错误", msg);
        }
    }
    /*获取储位列表*/
    private void selectStorage() {
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("deptId", application.getDeptId());
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.EMIAO(application.getBackSystem()));
        VaccineService vs = retrofit.create(VaccineService.class);
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = vs.getStorageInfoList(token, params);
        jsonForResultCall.enqueue(new getInventoryListCallback());
    }
    private class getInventoryListCallback implements Callback<JsonForResult> {

        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                if (response.code() != 200) {
                    UtilHelper.alertMsg(ConfigActivity.this, "错误", response.code() + response.message());
                    return;
                }
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess()) {
                    storageList = JSON.parseArray(jsonForResult.getData().toString(), Storage.class);
                } else {
                    if (jsonForResult != null) {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                }
            } catch (Exception e) {
                Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "网络异常!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            UtilHelper.alertMsg(ConfigActivity.this, "错误", msg);
        }
    }
    /*获取审批流列表*/
    private void selectApproval() {
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("deptId", application.getDeptId());
        params.put("category", "采购合同");
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.EMIAO(application.getBackSystem()));
        VaccineService vs = retrofit.create(VaccineService.class);
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = vs.getApprovalList(token, params);
        jsonForResultCall.enqueue(new getApprovalListCallback());
    }
    private class getApprovalListCallback implements Callback<JsonForResult> {
        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                if (response.code() != 200) {
                    UtilHelper.alertMsg(ConfigActivity.this, "错误", response.code() + response.message());
                    return;
                }
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess()) {
                    if(jsonForResult.getData()==null){
                        Toast.makeText(context,"审批流列表为空！", Toast.LENGTH_SHORT).show();
                    }else{
                        approvalList = JSON.parseArray(jsonForResult.getData().toString(), Approval.class);
                    }
                } else {
                    if (jsonForResult != null) {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                }
            } catch (Exception e) {
                Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                System.out.println(e.getStackTrace());
            }
        }
        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "网络异常!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            UtilHelper.alertMsg(ConfigActivity.this, "错误", msg);
        }
    }
    /*获取审批流列表*/
    private void selectRefDept() {
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("deptId", application.getDeptId());
        params.put("category", "采购合同");
        params.put("pageIndex", "0");
        params.put("pageSize", "50");
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.EMIAO(application.getBackSystem()));
        VaccineService vs = retrofit.create(VaccineService.class);
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = vs.getContactDeptList(token, params);
        jsonForResultCall.enqueue(new getRefDeptCallback());
    }
    private class getRefDeptCallback implements Callback<JsonForResult> {
        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                if (response.code() != 200) {
                    UtilHelper.alertMsg(ConfigActivity.this, "错误", response.code() + response.message());
                    return;
                }
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess()) {
                    refDeptList = JSON.parseArray(jsonForResult.getData().toString(), RefDept.class);
                } else {
                    if (jsonForResult != null) {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                }
            } catch (Exception e) {
                Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                System.out.println(e.getStackTrace());
            }
        }
        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "网络异常!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            UtilHelper.alertMsg(ConfigActivity.this, "错误", msg);
        }
    }

    private void show(TextView textView, List<String> name, List<String> id) {
        listView = new ListView(context);
        listView.setDivider(null);//设置分割线
        listView.setVerticalScrollBarEnabled(false);//不显示滑动条
        listView.setAdapter(new MyAdapter(textView,name, id));
        popup = new PopupWindow(context);
        popup.setWidth(textView.getWidth());
        popup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.selector_unfocused));
        popup.setContentView(listView);//设置显示内容
        popup.setOutsideTouchable(true);//点击PopupWindow以外的区域自动关闭该窗口
        popup.showAsDropDown(textView, 0, 5);//显示在edit控件的下面0,0代表偏移量
        textView.setBackgroundResource(R.drawable.selector_focused);
        popup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                textView.setBackgroundResource(R.drawable.selector_unfocused);
            }
        });
    }

    private class MyAdapter extends BaseAdapter {
        private List<String> name, id;private TextView textView;

        public MyAdapter(TextView textView,List<String> name, List<String> id) {
            this.name = name;
            this.id = id;
            this.textView = textView;
        }

        @Override
        public int getCount() {
            return name.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            HolderView holderView = null;
            if (convertView == null) {
                convertView = View.inflate(context, R.layout.item_dialog_login, null);
                holderView = new HolderView();
                holderView.text = (TextView) convertView.findViewById(R.id.tvStorage);
                convertView.setTag(holderView);
            } else {
                holderView = (HolderView) convertView.getTag();
            }

            holderView.text.setText(name.get(position));
            holderView.text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    textView.setText(name.get(position));
                    textView.setTextColor(getResources().getColor(R.color.billTextChoose));
                    if(textView==btnApprovalIn){
                        application.setConfigApprovalId(id.get(position));
                        application.setConfigApprovalName(name.get(position));
                    }else if(textView==btnPriceBookIn){
                        application.setConfigPriceId(id.get(position));
                        application.setConfigPriceNo(name.get(position));
                    }else if(textView==btnRefDept){
                        application.setConfigDeptId(id.get(position));
                        application.setConfigDeptName(name.get(position));
                    }else if(textView==btnStorage){
                        application.setConfigStorageId(id.get(position));
                        application.setConfigStorageName(name.get(position));
                    }else if(textView==btnVaccineType){
                        application.setConfigVaccineTypeId(id.get(position));
                        application.setConfigVaccineTypeName(name.get(position));
                    }else if(textView==btnBackSystem){
                        application.setBackSystem(id.get(position));
                    }
                    textView.setBackgroundResource(R.drawable.selector_unfocused);
                    popup.dismiss();
                }
            });
            return convertView;
        }
    }

    public class HolderView {//由于这里用户都是同一个人,就省略用户图像的刷新
        private TextView text;
    }

    private void showDialog(final View v, final int field, final String[] items, final Object values, String title) {
        //field:0-价格本 1-审批流程 2-疫苗类别 3-仓库储位 4-对接系统
        final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(v.getContext());
        final boolean isString = String.class.getName().equals(values.getClass().getComponentType().getName());

        final Object initValue = v.getTag();
        alertBuilder.setTitle(title);
        int checkedItem = 0;
        if (initValue != null) {
            for (int i = 0; i < items.length; i++) {
                if (isString) {
                    if (((String[]) values)[i].equals(initValue)) {
                        checkedItem = i;
                        break;
                    }
                } else {//整型数组
                    if (((Integer[]) values)[i] == initValue) {
                        checkedItem = i;
                        break;
                    }
                }
            }
        }
        alertBuilder.setSingleChoiceItems(items, checkedItem, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                ((Button) v).setText(items[i]);
                ((Button) v).setTag(isString ? ((String[]) values)[i] : ((Integer[]) values)[i]);
            }
        });

        alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (v.getTag() == null || ((Button) v).getText() == null || (isString == false && (Integer) v.getTag() < 0)) {
                    if (items.length > 0) {
                        ((Button) v).setText(items[0]);
                        ((Button) v).setTag(isString ? ((String[]) values)[0] : ((Integer[]) values)[0]);
                    } else {
                        return;
                    }
                }
                String key = v.getTag().toString();
                String value = ((Button) v).getText().toString();
                switch (field) {
                    case 0:
                        if (v.getId() == R.id.btnPriceBookIn) {
                            application.setPriceIdIn(key);
                            application.setPriceNoIn(value);
                            application.setPriceBookMstId(key);
                        }
                        break;
                    case 1:
                        if (v.getId() == R.id.btnApprovalIn) {
                            application.setApprovalIdIn(key);
                            application.setApprovalCategoryIn(value);
                        }
                        break;
                    case 2:
                        application.setVaccineType(key);
                        break;
                    case 3:
                        application.setStorageId(key);
                        application.setStorageName(value);
                        break;
                    case 4:
                        application.setBackSystem(key);
                        if (value.equals("测试系统")) {//如果是测试系统,就关闭这个Activity
                            logout();
                        }
                        break;
                }
                _alertDialog.dismiss();
            }
        });

        alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                ((Button) v).setTag(initValue);
                _alertDialog.dismiss();
            }
        });

        _alertDialog = alertBuilder.create();
        _alertDialog.show();
    }

}